package com.hiv.filter;

import com.hiv.context.SystemContext;
import com.hiv.context.SystemInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 上下文过滤器
 */
@Slf4j
@Component
public class ContextFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //
        addSysInfo(request);
        //
        filterChain.doFilter(request, response);
        //
        clean();
    }

    private void addSysInfo(HttpServletRequest request) {
        SystemInfo systemInfo = new SystemInfo();
        systemInfo.setReqPath(request.getRequestURI());
        systemInfo.setReqFullPath(request.getRequestURL().toString());
        //request.getContextPath() + request.getRequestURI() + "?" + request.getQueryString());
        systemInfo.setReferer(StringUtils.defaultIfEmpty(request.getHeader("Referer"), ""));
        systemInfo.setUserAgent(StringUtils.defaultIfEmpty(request.getHeader("User-Agent"), ""));

        String forwardedFor = request.getHeader("X-Forwarded-For");
        String forwardedIps = StringUtils.isNotBlank(forwardedFor) ? forwardedFor : request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(forwardedIps) && forwardedIps.split(",").length > 0) {
            systemInfo.setClientIp(forwardedIps.split(",")[0]);
        }

        String language = request.getHeader("Accept-Language");
        if(StringUtils.isNotEmpty(language)) {
            try {
                String[] split =language.split("-");
                systemInfo.setLocale(new Locale(split[0],split[1]));
            }catch (Exception e) {
                log.error("addSysInfo error", e);
            }
        }

        SystemContext.setSysContext(systemInfo);
    }

    private void clean() {
        SystemContext.clean();
    }

}
